package com.content.scaffold.common.mybatis;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import com.content.scaffold.common.identity.IdGenerator;
import com.content.scaffold.common.web.RequestContext;
import com.content.scaffold.common.web.RequestInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;


/**
 * @author xiaojl
 */
@Slf4j
public class CustomMetaObjectHandler implements MetaObjectHandler {

    private final IdGenerator idGenerator;

    public CustomMetaObjectHandler(IdGenerator idGenerator) {
        this.idGenerator = idGenerator;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            RequestInfo requestInfo = safeGetRequestInfo();
            setFieldValByName(BaseEntity.ID, idGenerator.nextId(), metaObject);
            setFieldValByName(BaseEntity.CREATED_TIME, new Date(), metaObject);
            if (ObjectUtil.isNotEmpty(requestInfo)) {
               //按需添加
            }
        } catch (Exception e) {

            log.error("填充基础字段失败", e);
            throw new RuntimeException("填充基础字段失败", e);
        }


    }

    private RequestInfo safeGetRequestInfo() {
        try {
            return RequestContext.getRequestInfo();
        } catch (Exception e) {
            log.warn("登陆信息为空，请确认是否登陆", e);
            return null;
        }
    }

    private void setFieldValIfNotNull(MetaObject metaObject, String fieldName, Object value) {
        if (value != null) {
            setFieldValByName(fieldName, value, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        RequestInfo requestInfo = RequestContext.getRequestInfo();

        setFieldValByName(BaseEntity.UPDATE_TIME, new Date(), metaObject);
    }
}
